import java.util.PriorityQueue;

//重写 计时器
class MyTimerTask2 implements Comparable<MyTimerTask2> {
    private Runnable runnable;
    private long time;

    public MyTimerTask2(Runnable runnable, long delay) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

    public long getTime() {
        return time;
    }

    public void run() {
        runnable.run();
    }

    @Override
    public int compareTo(MyTimerTask2 o) {
        return (int) (this.time - o.time);
    }
}

class MyTimer2 {
    //数据结构 -- 优先级队列
    PriorityQueue<MyTimerTask2> taskQueue = new PriorityQueue<>();
    // 创建锁
    Object locker = new Object();

    public void schedule(Runnable runnable, long delay) {
        synchronized (locker) {
            // 添加任务
            MyTimerTask2 timerTask2 = new MyTimerTask2(runnable, delay);
            taskQueue.offer(timerTask2);
            // 每添加一个 都要重新循环一次  找到最小的时间  放入小根堆
            locker.notify();
        }
    }

    public MyTimer2() {
        // 执行任务
        Thread t = new Thread(() -> {
            synchronized (locker) {
                while (true) {
                    try {
                        if (taskQueue.size() == 0) locker.wait();
                        MyTimerTask2 task2 = taskQueue.peek();
                        long curTime = System.currentTimeMillis();
                        if (curTime >= task2.getTime()) {
                            // 执行
                            task2.run();
                            taskQueue.poll();
                        } else {
                            // 还没到时间  阻塞等待  但是要放锁
                            locker.wait(task2.getTime() - curTime);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        t.start();
    }
}

public class Demo37 {
    public static void main(String[] args) {
        MyTimer2 timer2 = new MyTimer2();
        timer2.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        }, 3000);
        timer2.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 2000");
            }
        }, 2000);
        timer2.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 1000");
            }
        }, 1000);
    }
}
